import time
import hmac
import hashlib
import base64
import urllib.parse
import json
import sys
import subprocess
import requests




URL ="https://oapi.dingtalk.com/robot/send?access_token=c8e5bce77667739a966b598e5456bc72a02295f2605a42d1164055d9cd84fb1a"

 # 钉钉机器人文档说明
 # https://ding-doc.dingtalk.com/doc#/serverapi2/qf2nxq

def get_timestamp_sign():
    timestamp = str(round(time.time() * 1000))
    secret = "SEC3d3d6babc4431a3ef100fbb18d2ba31df44bb8c4c55495c168394b5a6e798f6b" # SEC开头的
    secret_enc = secret.encode('utf-8')
    string_to_sign = '{}\n{}'.format(timestamp, secret)
    string_to_sign_enc = string_to_sign.encode('utf-8')
    hmac_code = hmac.new(secret_enc, string_to_sign_enc,
                         digestmod=hashlib.sha256).digest()
    sign = urllib.parse.quote_plus(base64.b64encode(hmac_code))
    print("timestamp: ",timestamp)
    print("sign:",sign)
    return (timestamp, sign)


def get_signed_url():
    timestamp, sign = get_timestamp_sign()
    webhook = URL + "&timestamp="+timestamp+"&sign="+sign
    return webhook

def get_webhook(mode):

    if mode == 0: # only 敏感字
       webhook = URL
    elif mode == 1 or  mode ==2 : # 敏感字和加签 或 # 敏感字+加签+ip
        # 加签： https://oapi.dingtalk.com/robot/send?access_token=XXXXXX&timestamp=XXX&sign=XXX
        webhook = get_signed_url()
    else:
        webhook = ""
        print("error! mode:   ",mode,"  webhook :  ",webhook)
    return webhook

def get_message(content,is_send_all):
    # 和类型相对应，具体可以看文档 ：https://ding-doc.dingtalk.com/doc#/serverapi2/qf2nxq
    # 可以设置某个人的手机号，指定对象发送
    message = content
   # print(message)
    return message

def send_ding_message(content,is_send_all):

    # 请求的URL，WebHook地址
    webhook = get_webhook(1) # 主要模式有 0 ： 敏感字 1：# 敏感字 +加签 3：敏感字+加签+IP
    print("webhook: ",webhook)
    # 构建请求头部
    header = {
        "Content-Type": "application/json",
        "Charset": "UTF-8"
    }
    # 构建请求数据
    message = get_message(content,is_send_all)
    # 对请求的数据进行json封装
    message_json = json.dumps(message)
    # 发送请求
    info = requests.post(url=webhook, data=message_json, headers=header)
    # 打印返回的结果
    #print(info.text)
    print('钉钉发送')



if __name__ == "__main__":
    # 2、Link消息内容
    markdown_message = {
        "msgtype": "link", # link格式
        "link": {
            "title": "链接消息标题", # 链接标题
            "text": "这是一条链接消息，点击访问：", # 链接描述
            "messageUrl": "https://www.goofish.com/item?spm=a21ybx.search.searchFeedList.1.3110389cEPoURr&id=886329820143&categoryId=126856125", # 要访问的链接
            "picUrl": "https://img.alicdn.com/tfs/TB1NwmBEL9TBuNjy1zbXXXpepXa-2400-1218.png"  # 可选参数，链接消息的封面图片URL
        }
    }    

    test1 = {
        "msgtype":"feedCard",
        "feedCard": {
            "links": [
                  {
                "title": "链接消息标题", # 链接标题
                "text": "这是一条链接消息，点击访问：", # 链接描述
                "messageURL": "https://www.goofish.com/item?spm=a21ybx.search.searchFeedList.1.3110389cEPoURr&id=886329820143&categoryId=126856125", # 要访问的链接
                "picURL": "https://img.alicdn.com/tfs/TB1NwmBEL9TBuNjy1zbXXXpepXa-2400-1218.png"  # 可选参数，链接消息的封面图片URL
            }
           
            ]
        }
    }   

    test2 = {
        "msgtype": "feedCard",
        "feedCard": {
            "links": [
            {
                "title": "标题1",
                "messageURL": "https://example.com/link1",
                "picURL": "https://example.com/pic1.png"
            },
            {
                "title": "标题2",
                "messageURL": "https://example.com/link2",
                "picURL": "https://example.com/pic2.png"
            }
            ]
        }
    }        
    content     = "test,机器人测试,hello！"
    is_send_all = False
    send_ding_message(test1,is_send_all)

